import PathFind from "./PathFind";
import ResKeeper from "../../framework/res/ResKeeper"; 
import NodeUtil from "../../framework/utils/NodeUtil";
import Role from "../player/Role";

/**
 * 地图场景
 */
const {ccclass, property} = cc._decorator;

@ccclass
export default class MapScene extends ResKeeper {

    @property(PathFind)
    pathFind:PathFind = null;

    @property(Role)
    role:Role = null;

    @property(cc.Node)
    mapLayer:cc.Node = null;

    gx:number = 0; 

    async onLoad () { 
        let data:cc.Asset = await this.loadResAsync("map/map",cc.JsonAsset)
        let json:MapData = (data as cc.JsonAsset).json;
        this.pathFind.init(json); 
        this.gx = json.cellSize;  
        let startNode = cc.v2(10,15); 
        this.role.setTilePos( startNode)
        this.role.setGap(this.gx);
        this.role.init(startNode);
        this.onEvent();
    }
 
    onEvent(){ 
        this.mapLayer.on(cc.Node.EventType.TOUCH_END,this.onTouch,this); 
    }

    onTouch(e:cc.Event.EventTouch){ 
        var mainCamera = cc.Camera.findCamera( this.mapLayer );
        var tempPoint = new cc.Vec2(0, 0);
        mainCamera.getScreenToWorldPoint( e.getLocation(), tempPoint );
        var pos = this.mapLayer.convertToNodeSpaceAR( tempPoint );
        let nx = Math.floor( pos.x/ this.gx), ny =Math.floor(pos.y / this.gx); 
        let playerPos =  cc.v2(this.role.node.x,this.role.node.y); 
        let px = Math.floor( playerPos.x / this.gx), py =Math.floor(playerPos.y / this.gx);
        this.pathFind.setEndNode(cc.v2(px,py),cc.v2(nx,ny));
        let path = this.pathFind.search();   
        this.role.move(path,()=>{console.log("移动完成")}) 
    } 
}
